import hashlib
import json
import time

def md5(string):
    """计算字符串的 MD5 哈希值"""
    return hashlib.md5(string.encode('utf-8')).hexdigest()

def utf8_encode(string):
    """将字符串编码为 UTF-8 格式"""
    return string.replace('\r\n', '\n').encode('utf-8').decode('utf-8')

def base64_encode(string, encoding_key):
    """自定义 Base64 编码"""
    string = utf8_encode(string)
    result = []
    padding = 0
    for i in range(0, len(string), 3):
        chunk = string[i:i+3]
        if len(chunk) < 3:
            padding = 3 - len(chunk)
            chunk += '\0' * padding
        a, b, c = [ord(char) for char in chunk]
        # 计算 4 个 Base64 字符
        index1 = a >> 2
        index2 = ((a & 0x03) << 4) | (b >> 4)
        index3 = ((b & 0x0F) << 2) | (c >> 6)
        index4 = c & 0x3F
        # 处理填充
        if padding == 2:
            index3 = index4 = 64
        elif padding == 1:
            index4 = 64
        # 添加到结果
        result.extend([encoding_key[index1], encoding_key[index2], encoding_key[index3], encoding_key[index4]])
    return ''.join(result)

def en(e, t):
    """生成 X-s 和 X-t"""
    encoding_key = "A4NjFqYu5wPHsO0XTdDgMa2r1ZQocVte9UJBvk6/7=yRnhISGKblCWi+LpfE8xzm3"
    o = "test"  # 固定值
    a = int(time.time() * 1000)  # 当前时间戳（毫秒）

    # 处理输入参数 t
    if isinstance(t, (dict, list)):
        t_str = json.dumps(t, ensure_ascii=False)
    else:
        t_str = str(t) if t is not None else ""

    # 拼接字符串并计算 MD5
    pp = f"{a}{o}{e}{t_str}"
    md5_hash = md5(pp)

    # 自定义 Base64 编码
    x_s = base64_encode(md5_hash, encoding_key)
    return {
        "X-s": x_s,
        "X-t": a
    }

def get_xhs_headers(api, time_param=None):
    """暴露给外部的函数，生成小红书请求头"""
    return en(api, time_param)